<template>
  <div style="padding:16px;">
    <div style="display:flex;gap:12px;align-items:center;margin-bottom:12px;flex-wrap:wrap;">
      <h3 style="margin:0;">版本对比</h3>
      <el-select v-model="baseId" placeholder="源版本" filterable style="min-width:180px" @change="refresh">
        <el-option v-for="v in versions" :key="v._id || v.id" :label="v.versionTag" :value="v._id || v.id" />
      </el-select>
      <span>vs</span>
      <el-select v-model="targetId" placeholder="目标版本" filterable style="min-width:180px" @change="refresh">
        <el-option v-for="v in versions" :key="v._id || v.id" :label="v.versionTag" :value="v._id || v.id" />
      </el-select>
      <el-button type="primary" @click="refresh" :loading="loading">刷新对比</el-button>
      <el-button @click="window.print()">打印导出</el-button>
      <span style="color:#909399" v-if="errorTip">（{{ errorTip }}）</span>
    </div>

    <div v-if="summary" style="display:flex;gap:12px;margin-bottom:12px;flex-wrap:wrap;align-items:center;">
      <el-tag type="success">新增 {{ summary.added || 0 }}</el-tag>
      <el-tag type="danger">删除 {{ summary.removed || 0 }}</el-tag>
      <el-tag type="warning">修改 {{ summary.modified || 0 }}</el-tag>
      <el-tag>顺序 {{ summary.reordered || 0 }}</el-tag>
      <div class="legend">
        <span class="legend-item added">新增</span>
        <span class="legend-item removed">删除</span>
        <span class="legend-item modified">修改</span>
      </div>
    </div>

    <div style="display:flex;gap:12px;">
      <div ref="leftRef" class="pane">
        <div class="pane-title">源版本（{{ baseLabel }}）</div>
        <VersionDiffTree :snapshot="baseSnap" :changed-ids="changedIds" :changes="changes" />
      </div>
      <div ref="rightRef" class="pane">
        <div class="pane-title">目标版本（{{ targetLabel }}）</div>
        <VersionDiffTree :snapshot="targetSnap" :changed-ids="changedIds" :changes="changes" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { api } from '@/utils/api'
import VersionDiffTree from '@/components/VersionDiffTree.vue'

const route = useRoute()
const projectId = route.params.projectId

const versions = ref([])
const baseId = ref(route.query.base || '')
const targetId = ref(route.query.target || '')

const baseSnap = ref(null)
const targetSnap = ref(null)
const summary = ref(null)
const changedIds = ref({ sections: [], forms: [], fields: [], frontMatters: [] })
const changes = ref(null)
const loading = ref(false)
const errorTip = ref('')

const labelOf = (id) => (versions.value.find(v => (v._id || v.id) === id)?.versionTag) || '-'
const baseLabel = computed(() => labelOf(baseId.value))
const targetLabel = computed(() => labelOf(targetId.value))

const loadVersions = async () => {
  versions.value = await api.versions.list(projectId)
  if (!baseId.value && versions.value.length >= 2) baseId.value = versions.value[1]._id || versions.value[1].id
  if (!targetId.value && versions.value.length >= 1) targetId.value = versions.value[0]._id || versions.value[0].id
}

const refresh = async () => {
  if (!baseId.value || !targetId.value) return
  loading.value = true; errorTip.value = ''
  try {
    const [b, t] = await Promise.all([
      api.versions.get(projectId, baseId.value),
      api.versions.get(projectId, targetId.value)
    ])
    baseSnap.value = b?.snapshot || b
    targetSnap.value = t?.snapshot || t

    try {
      const res = await api.versions.compare(projectId, { baseVersionId: baseId.value, targetVersionId: targetId.value })
      summary.value = res?.summary || null
      changedIds.value = res?.changedIds || { sections: [], forms: [], fields: [], frontMatters: [] }
      changes.value = res?.changes || null
    } catch {
      summary.value = null
      changedIds.value = { sections: [], forms: [], fields: [], frontMatters: [] }
      errorTip.value = '后端对比接口未就绪，仅展示并排预览'
    }
  } catch (e) {
    ElMessage.error(e.message || '加载版本数据失败')
  } finally {
    loading.value = false
  }
}

const leftRef = ref(null)
const rightRef = ref(null)
const sync = (from, to) => {
  const ratio = from.scrollTop / (from.scrollHeight - from.clientHeight || 1)
  to.scrollTop = ratio * (to.scrollHeight - to.clientHeight)
}

onMounted(async () => {
  await loadVersions()
  await refresh()
  leftRef.value?.addEventListener('scroll', () => sync(leftRef.value, rightRef.value))
  rightRef.value?.addEventListener('scroll', () => sync(rightRef.value, leftRef.value))
})
</script>

<style scoped>
.pane { flex:1; min-height:70vh; border:1px solid #e4e7ed; border-radius:6px; padding:8px; overflow:auto; background:#fff; }
.pane-title { font-weight:600; margin:4px 0 8px 2px; }
.legend { display:inline-flex; gap:8px; margin-left:12px; font-size:12px; color:#666; }
.legend-item { padding:2px 6px; border-radius:3px; }
.legend-item.added { background:#f0f9eb; border-left:3px solid #67c23a; }
.legend-item.removed { background:#fef0f0; border-left:3px solid #f56c6c; }
.legend-item.modified { background:#fff7e6; border-left:3px solid #e6a23c; }
</style>




